﻿using System;
using DevExpress.Web.ASPxGridView;
using ExpressionEngine;

namespace ASPxGridViewExpressionSummary
{
    public class ExpressionSummary : ASPxSummaryItem
    {
        public ExpressionSummary()
        {
            SummaryType = DevExpress.Data.SummaryItemType.Custom;
        }

        public string Expression
        {
            get { return Convert.ToString(ViewState["Expression"]); }
            set { ViewState.Add("Expression", value); }
        }

        internal object Start()
        {
            AggregateExpressionEvaluator aggregateExpression = new AggregateExpressionEvaluator(Expression);
            aggregateExpression.Reset();
            return aggregateExpression;
        }

        internal void RowChanged(object state, IValueProvider rowData)
        {
            ((AggregateExpressionEvaluator)state).RowChanged(rowData);
        }

        internal object GetResult(object state)
        {
            try
            {
                return ((AggregateExpressionEvaluator)state).GetResult();
            }
            catch (DivideByZeroException)
            {
                return double.NaN;
            }
        }
    }
}
